import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/ui/my/order/my_order_list_page.dart';
import 'package:gold/ui/my/order/order_config.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:02 2024/12/12

class MyOrderPage extends StatelessWidget {
  /// 订单类型
  late final ValueNotifier<String> _typeNotifier;
  /// 订单状态
  late final ValueNotifier<String?> _statusNotifier;
  /// 页面长度
  late final ValueNotifier<int> _pageNotifier;

  /// product=商品订单,gold=黄金投资订单,points=积分商品订单
  final String orderType;

  /// 滚动到指定位置
  late final AutoScrollController _scrollController = AutoScrollController();

  late final List<PageData> _keys;

  late final PageController _controller;

  /// 已授权页面信息
  final authorizedPageData = PageData(GlobalKey<MyOrderListState>(), OrderStatus.authorized);

  MyOrderPage({super.key, required this.orderType, required String? orderStatus}) {
    _typeNotifier = ValueNotifier(orderType);
    _statusNotifier = ValueNotifier(orderStatus);
    _keys = [
      PageData(GlobalKey<MyOrderListState>(), null), PageData(GlobalKey<MyOrderListState>(), OrderStatus.paying),
      PageData(GlobalKey<MyOrderListState>(), OrderStatus.sending), PageData(GlobalKey<MyOrderListState>(), OrderStatus.receiving),
      PageData(GlobalKey<MyOrderListState>(), OrderStatus.done), PageData(GlobalKey<MyOrderListState>(), OrderStatus.reviewing),
      PageData(GlobalKey<MyOrderListState>(), OrderStatus.cancel),
    ];
    if (orderType == ProductType.gold) _keys.insert(4, authorizedPageData);
    _pageNotifier = ValueNotifier(_keys.length);
    _controller = PageController(initialPage: getOrderStatusIndex(orderType, orderStatus));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: xfgAppbar(title: '我的订单'),
      backgroundColor: XfgColor.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              height: XfgSize().size34,
              decoration: BoxDecoration(color: XfgColor.colorF2, borderRadius: BorderRadius.circular(XfgSize().size34)),
              child: ValueListenableBuilder<String>(
                valueListenable: _typeNotifier,
                builder: (_, type, __) => Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _orderTypeWidget('购物', ProductType.product, type),
                    _orderTypeWidget('黄金', ProductType.gold, type),
                    _orderTypeWidget('积分', ProductType.points, type)
                  ]
                ),
              )
          ),
          /// 订单状态
          SizedBox(
            height: XfgSize().size52,
            child: ValueListenableBuilder<String?>(
                valueListenable: _statusNotifier,
                builder: (_, status, __) => ValueListenableBuilder<int>(
                  valueListenable: _pageNotifier,
                  builder: (_, length, __) => ListView.builder(
                    scrollDirection: Axis.horizontal,
                    controller: _scrollController,
                    itemCount: length,
                    itemBuilder: (_, index) {
                      final key = _keys[index];
                      final select = status == key.orderStatus;
                      return AutoScrollTag(
                        key: ValueKey(index),
                        controller: _scrollController,
                        index: index,
                        child: GestureDetector(
                            onTap: () {
                              if (!select) {
                                _statusNotifier.value = key.orderStatus;
                                _controller.jumpToPage(index);
                                _keys[index].key.currentState?.refreshOrderType(_typeNotifier.value);
                                _scrollController.scrollToIndex(index);
                              }
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Padding(
                              padding: EdgeInsets.symmetric(horizontal: XfgSize().size12),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  XfgText(getOrderStatusDesc(_typeNotifier.value, key.orderStatus), fontSize: XfgSize().text14, color: XfgColor.text1, bold: select ? FontWeight.bold:null),
                                  SizedBox(height: XfgSize().size10),
                                  Container(height: XfgSize().size3, width: XfgSize().size20, decoration: select ? BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size3)):null),
                                  SizedBox(height: XfgSize().size5)
                                ],
                              ),
                            )
                        ),
                      );
                    },
                  ),
                )
            ),
          ),
          Expanded(
            child: Container(
              color: XfgColor.background,
              child: ValueListenableBuilder<int>(
                valueListenable: _pageNotifier,
                builder: (_, length, __) => PageView.builder(
                    controller: _controller,
                    onPageChanged: (index) {
                      _statusNotifier.value = _keys[index].orderStatus;
                      _scrollController.scrollToIndex(index);
                    },
                    itemCount: length,
                    itemBuilder: (_, index) {
                      final key = _keys[index];
                      return MyOrderListPage(
                          key: key.key,
                          orderType: orderType,
                          orderStatus: key.orderStatus,
                          onInit: (data) => data.orderType = _typeNotifier.value
                      );
                    }
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 订单类型通用布局
  Widget _orderTypeWidget(String text, String newType, String select) => GestureDetector(
    onTap: () {
      if (newType != select) {
        if (newType == ProductType.gold) {
          _keys.insert(4, authorizedPageData);
          _pageNotifier.value = _keys.length;
        } else {
          if (select == ProductType.gold) {
            _keys.removeAt(4);
            _pageNotifier.value = _keys.length;
          }
        }
        _typeNotifier.value = newType;
        _statusNotifier.value = null;
        _controller.jumpToPage(0);
        _keys[0].key.currentState?.refreshOrderType(newType);
      }
    },
    behavior: HitTestBehavior.opaque,
    child: Container(
      width: XfgSize().size95,
      decoration: select == newType ? BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size34)):null,
      alignment: Alignment.center,
      child: XfgText(text, fontSize: XfgSize().text16, color: select == newType ? XfgColor.white:XfgColor.text1, bold: FontWeight.bold),
    ),
  );
}

class PageData {
  final GlobalKey<MyOrderListState> key;
  final String? orderStatus;

  PageData(this.key, this.orderStatus);
}

